﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace PIM_ATE.Electrical
{
    public partial class FrmManualELEC : Form
    {
        public FrmManualELEC(ClsDataUser user)
        {
            InitializeComponent();
            m_userObj = user;
            m_pim_resultObj = new ClsDataResultForAntennaBuilder(GDefine.DBNameELEC);
            m_selectBuilder = new ClsDataConfigSelectBuilder(GDefine.DBNameELEC);
            m_cTestConfigBuilder = new ClsDataSParamBuilder(GDefine.DBNameELEC);
            m_dicResults = new Dictionary<int, JcELECDataResults>();
        }

        Label[] ctl_config_list_lblName;
        TextBox[] ctl_config_list_tBItemValue;

        //获取配置实例
        ClsDataSParamBuilder m_cTestConfigBuilder;
        ClsDataConfigSelectBuilder m_selectBuilder;
        //上传数据实例
        ClsDataResultForAntennaBuilder m_pim_resultObj;
        //Dictionary<int, JcPIMDataMaxResult> m_pim_dicResults;
        Dictionary<int, JcELECDataResults> m_dicResults;
        //配置列表
        List<clsTestItem> m_testConfig;
        DataTable m_dtTestItem;
        //用户
        ClsDataUser m_userObj;
        ClsDataProduct productObj;

        private void FrmManual_Load(object sender, EventArgs e)
        {
            cbPIMStep.SelectedIndex = 0;
        }

        private void ctl_main_btnSet_Click(object sender, EventArgs e)
        {
            if (tbProductSN.Text == "") return;
            if (initDataConfig_for_antenna(tbProductSN.Text))
            {
                ptlControls.Controls.Clear();
                createCtl();
            }

        }

        private bool initDataConfig_for_antenna(string sProductSN)
        {
            productObj = new ClsDataProduct();
            productObj.sProductSN = sProductSN;

            if (!m_pim_resultObj.matchSN(productObj))
            {//匹配条码
                MessageBox.Show("该条码无法匹配产品代码!");
                return false;
            }

            ClsDataConfigSelectBuilder m_selectBuilder = new ClsDataConfigSelectBuilder(GDefine.DBNameELEC);
            m_selectBuilder.construct(productObj.sMOID);
            List<bool> lstEnable = m_selectBuilder.downloadELECSelect();
            if (lstEnable == null)
            {//查询配置可选
                MessageBox.Show("该条码无法查询配置可选!");
                return false;
            }
            productObj.enableConfig = lstEnable;

            m_userObj.aSpecial = m_selectBuilder.downladSpecial();
            if (m_userObj.aSpecial == null)
            { //查询数据特采
                MessageBox.Show("该条码无法查询数据特采!");
                return false;
            }

            m_cTestConfigBuilder.constructByProcode(productObj.sProcode);
            if (m_cTestConfigBuilder.construct(productObj.sProcode, "1.0"))
            {//下载配置
                m_dtTestItem = m_cTestConfigBuilder.download(out m_testConfig);
            }
            else
            {
                MessageBox.Show("未发现配置：" + productObj.sProcode);
                return false;
            }

            if (!m_pim_resultObj.constructSN(tbProductSN.Text, cbPIMStep.Text, m_userObj, true))
            {
                MessageBox.Show("条码数据检测失败：" + m_pim_resultObj.error());
                return false;
            }

            if (m_dtTestItem == null || m_dtTestItem.Rows.Count == 0)
            {
                MessageBox.Show("产品代码的配置为空或不存在!");
                return false;
            }

            if (productObj.enableConfig.Count == 0)
            {//无配置时
                for (int i = 0; i < m_dtTestItem.Rows.Count; i++)
                    productObj.enableConfig.Add(true);
            }
            else
            {
                if (m_dtTestItem.Rows.Count != productObj.enableConfig.Count)
                {//配置数量错误
                    MessageBox.Show("产品代码的可选配置错误！");
                    return false;
                }
            }

            ctl_main_tbProCode.Text = productObj.sProcode;

            return true;
        }

        private bool matchProcode(ClsDataProduct product)
        {
            if (!m_pim_resultObj.matchSN(product))
            {//匹配条码
                return false;
            }

            m_selectBuilder.construct(product.sMOID);
            List<bool> lstEnable = m_selectBuilder.downloadPIMSelect();
            if (lstEnable == null)
            {//查询配置可选
                return false;
            }
            product.enableConfig = lstEnable;

            return true;
        }

        private void createCtl()
        {
            ptlControls.RowCount = m_testConfig.Count / 2 + 1;
            ctl_config_list_lblName = new Label[m_testConfig.Count];
            ctl_config_list_tBItemValue = new TextBox[m_testConfig.Count];

            for (int i = 0; i < m_testConfig.Count; i++)
            {
                if (!productObj.enableConfig[i]) continue;

                ctl_config_list_lblName[i] = new Label();
                ctl_config_list_lblName[i].Anchor = AnchorStyles.None;
                ctl_config_list_lblName[i].AutoSize = true;
                ctl_config_list_lblName[i].Size = new System.Drawing.Size(47, 12);
                ctl_config_list_lblName[i].Text = m_testConfig[i].sTestName + "/" +
                                                  m_testConfig[i].sPortA_RCU + "/" +
                                                  m_testConfig[i].sPortB_RCU + "/" + m_testConfig[i].sSpec;

                //ctl_config_list_lblName[i].Text = m_pim_lstCfgData_local[i].PIMItemName;

                ptlControls.Controls.Add(ctl_config_list_lblName[i]);

                ctl_config_list_tBItemValue[i] = new TextBox();
                ctl_config_list_tBItemValue[i].Anchor = AnchorStyles.Left | AnchorStyles.Right;

                ptlControls.Controls.Add(ctl_config_list_tBItemValue[i]);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            bool isAllNull = true;

            if (productObj == null || productObj.sProductSN == "")
            {
                MessageBox.Show("请输入条码和信息后设定!");
                return;
            }

            if (tbProductSN.Text == "" || cbPIMStep.SelectedIndex < 0)
            {
                MessageBox.Show("请输入条码和信息!");
                return;
            }

            try
            {
                for (int i = 0; i < m_testConfig.Count; i++)
                {
                    if (!productObj.enableConfig[i]) continue;
                    if (ctl_config_list_tBItemValue[i].Text.Replace(" ", "") == "")
                    {
                        MessageBox.Show("请完整输入，不测试的项目请输入0");
                        return;
                    }

                    float max = Convert.ToSingle(ctl_config_list_tBItemValue[i].Text);
                    if (max == 0) continue;
                    //if (max > 0) max = max * -1;
                    bool bResult = !PIMFunction.GetResult(m_testConfig[i].sFactSpec, max, max);

                    JcELECDataResults result = new JcELECDataResults();
                    result.fValue = max;
                    result.sPass = bResult ? GDefine.ContentFail : GDefine.ContentPass;
                    m_dicResults.Add(i, result);
                    isAllNull = false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("测试值的数据格式不正确，请检查!");
                return;
            }

            if (isAllNull)
            {
                MessageBox.Show("没有测试值，请输入!");
                return;
            }

            bool resultPass = false; string sTime = "";
            if (!GDefine.IS_UploadElecNew)
            {

                foreach (var obj in m_dicResults)
                {
                    if (obj.Value.sPass == "FAIL")
                    {
                        resultPass = false;
                        break;
                    }
                }


                JcInstrument m_Instr = new JcInstrument();
                if (m_dtTestItem.Rows[0][clsTestItem.chn_RCUFlag].ToString().Trim() == "0")
                {//根据配置设置是否使用RCU
                    m_Instr.RCU_Type = 0;
                    m_Instr.RCU_Check = 0;
                }
                else if (m_dtTestItem.Rows[0][clsTestItem.chn_RCUFlag].ToString().Trim() == "1")
                {
                    m_Instr.RCU_Type = 1;
                    m_Instr.RCU_Check = 1;
                }
                else
                {
                    m_Instr.RCU_Type = 1;
                    m_Instr.RCU_Check = 0;
                }


                int id; DateTime time;
                ClsDataAllStatus AllStatus = new ClsDataAllStatus();
                AllStatus.ProductSN = productObj.sProductSN.ToUpper();
                AllStatus.Status = resultPass == true ? GDefine.ContentPass : GDefine.ContentFail;
                if (!UploadAllStatus(AllStatus, out id, out time))
                {
                    MessageBox.Show("上传数据(整体)失败", "Err");
                    return;
                }

                if (m_Instr.RCU_Type != 0 && m_Instr.RCU_Check == 1)
                {
                    ClsDataCodeStatus CodeStatus = new ClsDataCodeStatus();
                    CodeStatus.ProductSN = productObj.sProductSN.ToUpper();
                    CodeStatus.AllStatusId = id;
                    CodeStatus.Time = time;
                    CodeStatus.Status = resultPass == true ? GDefine.ContentPass : GDefine.ContentFail;
                    if (!UploadCodeStatus(CodeStatus))
                    {
                        MessageBox.Show("上传数据(条码检测)失败", "Err");
                        return;
                    }
                }

                ClsDataWaveStatus WaveStatus = new ClsDataWaveStatus();
                WaveStatus.ProductSN = productObj.sProductSN.ToUpper();
                WaveStatus.AllStatusId = id;
                WaveStatus.Time = time;
                WaveStatus.Status = resultPass == true ? GDefine.ContentPass : GDefine.ContentFail;
                if (!UploadWaveStatus(WaveStatus))
                {
                    MessageBox.Show("上传数据(波形监控)失败", "Err");
                    return;
                }

                if (m_Instr.RCU_Type != 0)
                {
                    ClsDataRCUCheck rcucheck = new ClsDataRCUCheck();
                    rcucheck.ProductSN = productObj.sProductSN.ToUpper();
                    rcucheck.AllStatusId = id;
                    rcucheck.Time = time;
                    rcucheck.Status = resultPass == true ? GDefine.ContentPass : GDefine.ContentFail;
                    if (!UploadCalRcuStatus(rcucheck))
                    {
                        MessageBox.Show("上传数据(RCU校准)失败", "Err");
                        return;
                    }
                }


                sTime = time.ToString("yyyy-MM-dd HH:mm:ss.fff");
                if (m_pim_resultObj.uploadElecNew(m_dtTestItem, m_dicResults, ref resultPass, ref sTime, id))
                {
                    string v = resultPass ? "合格" : "失败";
                    MessageBox.Show("上传成功！" + " 测试:" + v);
                    btnClear_Click(null, null);
                    return;
                }

            }
            else
            {
                if (m_pim_resultObj.uploadElec(m_dtTestItem, m_dicResults, ref resultPass))
                {
                    string v = resultPass ? "合格" : "失败";
                    MessageBox.Show("上传成功！" + " 测试:" + v);
                    btnClear_Click(null, null);
                    return;
                }
            }
        }
        bool UploadAllStatus(ClsDataAllStatus Status, out int id, out DateTime time)
        {
            ClsDataAllStatusBuilder all = new ClsDataAllStatusBuilder(GDefine.DBNameELEC);
            all.construct(Status);
            bool res = all.updateStatus(out id, out time);
            return res;
        }
        bool UploadCodeStatus(ClsDataCodeStatus Status)
        {
            ClsDataCodeStatusBuilder all = new ClsDataCodeStatusBuilder(GDefine.DBNameELEC);
            all.construct(Status);
            bool res = all.updateStatus();
            return res;
        }
        bool UploadWaveStatus(ClsDataWaveStatus Status)
        {
            ClsDataWaveStatusBuilder all = new ClsDataWaveStatusBuilder(GDefine.DBNameELEC);
            all.construct(Status);
            bool res = all.updateStatus();
            return res;
        }
        private bool UploadCalRcuStatus(ClsDataRCUCheck RCUCheck)
        {
            ClsDataRCUCheckBuilder rcuCheck = new ClsDataRCUCheckBuilder(GDefine.DBNameELEC);
            return rcuCheck.updateStatus(RCUCheck);
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            tbProductSN.Text = "";
            ctl_main_tbProCode.Text = "";
            m_dicResults.Clear();
            ptlControls.Controls.Clear();
            productObj = null;
            //foreach (var item in ctl_config_list_tBItemValue)
            //{
            //    item.Text = "";
            //}
        }

        private void tbProductSN_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                ctl_main_btnSet_Click(sender, e);
            }
        }

    }
}
